package cn.com.franke.concurrency;

import com.google.common.util.concurrent.RateLimiter;
import org.junit.Test;

import java.util.concurrent.TimeUnit;

/**
 * Created by liuzh on 2017/5/1.
 */
public class RateLimiterTest {
    RateLimiter limiter = RateLimiter.create(4.0); //每秒不超过4个任务被提交

    //limiter.acquire();  //请求RateLimiter, 超过permits会被阻塞
//executor.submit(runnable); //提交任务
    @Test
    public void test() {
        for (int i = 0; i < 10; i++) {
            try {
                TimeUnit.MILLISECONDS.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            new Thread(new Runnable() {
                @Override
                public void run() {
                    if (limiter.tryAcquire()) { //未请求到limiter则立即返回false
                        System.out.println("acquire");
                        try {
                            TimeUnit.SECONDS.sleep(3);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    } else {
                        System.out.println("notacquire");
                    }
                }
            }).start();
        }
        try {
            TimeUnit.SECONDS.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
